/*
 * @lc app=leetcode.cn id=116 lang=javascript
 *
 * [116] 填充每个节点的下一个右侧节点指针
 */

// @lc code=start
/**
 * // Definition for a Node.
 * function Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {Node} root
 * @return {Node}
 */
var connect = function (root) {
  if (root === null) return root
  let queque = [root]
  while (queque.length) {
    let n = queque.length
    for (let i = 0; i < n; i++){
      let node = queque.shift()
      if (i < n - 1) {
        node.next=queque[0]
      }
      node.left&&queque.push(node.left)
      node.right&&queque.push(node.right)
    }
  }
  return root
};
// @lc code=end

